using AngleSharp;
using ElectronNetPlayerJpys.Common;
using ElectronNetPlayerJpys.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace ElectronNetPlayerJpys.Controllers
{
    [Route("/")]
    public class HomeController : Controller
    {
        public static string baseUrl = "https://www.jpys.me";

        // 缓存详情页地址
        public static string getDetailUrl = "";
        // 缓存详情页数据
        public static VideoDetailInfo detailData = null;

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取首页数据
        /// </summary>
        /// <param name="url">首页地址</param>
        /// <returns>首页数据</returns>
        [HttpGet]
        [Route("GetHomeData")]
        public JsonResult GetHomeData(string url)
        {
            // 存储视频信息
            List<VideoInfo> videoInfos = new List<VideoInfo>();
            // 获取hhtml
            string htmlCode = Http.Get(url);

            // 解析document
            //var config = Configuration.Default;
            //var context = BrowsingContext.New(config);
            //var document = context.OpenAsync(req => req.Content(htmlCode)).Result;

            var document = ParseHtml.GetDocument(htmlCode);


            // 获取视频列表
            var vodlist = document.QuerySelectorAll("ul.myui-vodlist.clearfix li");

            foreach (var vod in vodlist)
            {
                var atag = vod.QuerySelector("a.myui-vodlist__thumb.lazyload");
                string name = atag.Attributes["title"].Value;
                string href = atag.Attributes["href"].Value;


                var dateInfo = vod.QuerySelector("span.pic-text.text-right");
                string date = dateInfo.TextContent;
                videoInfos.Add(new VideoInfo { Name = name, Url = baseUrl + href, Date = date });
            }


            //// 总页数 --------120---.html
            //var totalPageUrl = document.QuerySelector("ul.myui-page.text-center.clearfix li:nth-child(10) a").Attributes["href"].Value;
            //string totalPage = StringHelper.GetTextGainCenter("--------", "---.html", totalPageUrl);


            // 获取总页数
            var total = document.QuerySelector("ul.myui-page li.visible-xs a").InnerHtml;
            var totalPage = total.Substring(total.IndexOf('/')+1);
            //Console.WriteLine(totalPage);

            return Json(new { data = videoInfos, totalPage = totalPage, count = videoInfos.Count });
        }

        /// <summary>
        /// 获取详情页数据
        /// </summary>
        /// <param name="url">详情页地址</param>
        /// <returns>详情页数据</returns>
        [HttpGet]
        [Route("GetDetail")]
        public JsonResult GetDetail(string url)
        {
            // 判断是否缓存
            if (getDetailUrl != "" && getDetailUrl == url && detailData != null)
            {
                Console.WriteLine("走了缓存...");
                // 直接返回已缓存的数据
                return Json(new { data = detailData });
            }
            // 缓存当前请求地址
            getDetailUrl = url;

            VideoDetailInfo detailInfo = new VideoDetailInfo();
            string htmlCode = Http.Get(url);

            // 解析html
            var document = ParseHtml.GetDocument(htmlCode);

            // 视频简介
            var postContent = document.QuerySelector("div.myui-panel-box.clearfix div:nth-child(2)");
            // 移除操作按钮
            var operate = postContent.QuerySelector("div.myui-content__operate");
            if (operate != null)
            {
                postContent.RemoveChild(operate);
            }
            
            
            // 获取图片真实地址
            var imgSrc = document.QuerySelector("img.lazyload").Attributes["data-original"].Value;
            // 简介信息
            var summary = postContent.InnerHtml;
            summary = summary.Replace("/template/mytheme/statics/img/load.png", imgSrc);
            detailInfo.Introduction = summary;

            // 视频名称
            var title = StringHelper.GetTextGainCenter("<h1 class=\"title\">", "</h1>", summary);
            // Console.WriteLine(title);
            detailInfo.Title = title;

            // 播放链接
            var pus = document.QuerySelectorAll("div.tab-pane.fade.in.clearfix a");

            foreach (var pu in pus)
            {
                // 集数
                var episode = pu.InnerHtml;
                // 播放地址
                var address = pu.Attributes["href"].Value;
                detailInfo.PlayInfo.Add(new PlayInfo{ Episode = episode, Address = baseUrl + address });
            }

            // 缓存数据
            detailData = detailInfo;
            return Json(new { data = detailInfo });
        }


        /// <summary>
        /// 获取真实播放地址
        /// </summary>
        /// <param name="url">待解析的地址</param>
        /// <returns>真实播放地址</returns>
        [HttpGet]
        [Route("GetRealUrl")]
        public JsonResult GetRealUrl(string url)
        {
            string htmlCode = Http.Get(url);
            // 解析html
            var document = ParseHtml.GetDocument(htmlCode);

            // 存真实地址的script
            var realUrlScript = document.QuerySelector("div.myui-player__box script:nth-child(1)").InnerHtml;
            
            // 真实地址
            Match match = Regex.Match(realUrlScript, "\"url\":\"(.*?)\"");
            string realUrl = match.Groups[1].Value.Replace("\\", "");
            // Console.WriteLine(realUrl);

            return Json(new { data = realUrl });
        }
    }
}
